#pragma once
#include <iostream>
#include <string>
#include "myh/socket.hpp"
#include "myh/MyLog.hpp"
#include "myh/pthreadpool.hpp"

class udpserve
{
    typedef void (*task)();
    typedef std::shared_ptr<udpserve> UdpPtr;
    typedef std::shared_ptr<Socket> SocketPtr;
    void funrun()
    {
    }
    static const char *defaultip;

public:
    void run()
    {
        _this->_csocket->Bind();
        sockaddr_in clientaddr;
        std::string s;
        lg.ChangeFilePath(Screnn);
        while (true)
        {
            lg(Debug, "[%s-%d][%s ... ]", __FILE__, __LINE__,"等待客户端链接");
            s = _this->_csocket->Recvform(&clientaddr);
            char ip[16];
            inet_ntop(AF_INET,&clientaddr.sin_addr,ip,16);
            uint16_t port = ntohl(clientaddr.sin_port);
            lg(Debug, "[%s-%d][ip->%s---port->%ld][%s]", __FILE__, __LINE__,ip,port,s.c_str());
            _this->_csocket->Sendto(s, &clientaddr);
        }
    }

    static UdpPtr Getinitance(uint16_t port = 0, const std::string &ip = defaultip,int domain = AF_INET)
    {
        static std::once_flag once;
        std::call_once(once, [port, ip, domain]()
                       { _this = UdpPtr(new udpserve(port, ip, domain)); });
        return _this;
    }

private:
    udpserve(const udpserve &u) = delete;
    udpserve &operator=(const udpserve &u) = delete;
    udpserve(uint16_t port, const std::string &ip = defaultip, int domain = AF_INET)
        : _csocket(SocketPtr(new Socket(port, ip, domain,SOCK_DGRAM)))
    {
    }

private:
    SocketPtr _csocket;
    static UdpPtr _this;
};

udpserve::UdpPtr udpserve::_this = nullptr;
const char * udpserve::defaultip = "0.0.0.0";
